package com.xudm.cdg.utils;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.sql.Types;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class MyGenerateUtils {
    //数据库连接信息
    static String url = "jdbc:mysql://localhost:3306/xudm_cosmic_document_generate?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8",
            username = "root",
            password = "xudm123456";

    // 设置作者
    static String author = "xudm";
    // 指定输出目录
    static String outputDir = "D:\\DevelopSpace\\IDEASpace\\outputDir";

    // 设置父包名
    static String parent = "com.xudm.cdg";
    // 表前缀
    static String[] tablePrefix = {"t_cdg_"};
    // 字段前缀
    static String[] fieldPrefix = {"f_"};
    //自动填充字段
    static Column[] fillColumns = new Column[]{
            new Column("f_updated_time", FieldFill.INSERT_UPDATE),
            new Column("f_created_time", FieldFill.INSERT),
            new Column("created_time", FieldFill.INSERT),
            new Column("updated_by", FieldFill.INSERT_UPDATE),
            new Column("updated_time", FieldFill.INSERT_UPDATE),
            new Column("created_by", FieldFill.INSERT),
            new Column("f_created_by", FieldFill.INSERT),
            new Column("f_delete_flag", FieldFill.INSERT),
            new Column("delete_flag", FieldFill.INSERT),
            new Column("f_status", FieldFill.INSERT),
            new Column("status", FieldFill.INSERT),
    };


    public static void main(String[] args) {
        // 项目名 例如app  web
        String busniessName = "system";
        generatorByBusinessModule(busniessName, new String[]{"t_cdg_basic_config", "t_cdg_operation_log", "t_cdg_file_generation_record"});
    }

    /**
     * @param businessModuleName 业务模块名称，可以为空
     * @param generatorTables    需要生成的表名称
     */
    private static void generatorByBusinessModule(String businessModuleName, String[] generatorTables) {

        String convertName = StringUtils.isBlank(businessModuleName) ? businessModuleName : "." + businessModuleName;

        //设置 entity 包名
        String entityPackageName = "entity" + convertName;
        //设置 controller 包名
        String controllerPackageName = "controller";
        //设置 service 包名
        String servicePackageName = "service" + convertName;
        //设置 serviceImpl 包名
        String serviceImplPackageName = "service.Impl" + convertName;
        //设置 mapper 包名
        String mapperPackageName = "mapper" + convertName;

        // 设置mapperXml生成路径
        String mapperXmlPath = outputDir + "/mapper/" + businessModuleName;

        // 设置 service 父类
        String superServiceName = "com.baomidou.mybatisplus.extension.service.IService";
        // 设置 serviceImpl 父类
        String superServiceImplName = "com.baomidou.mybatisplus.extension.service.impl.ServiceImpl";

        FastAutoGenerator.create(url, username, password)
                .globalConfig(builder -> {
                    builder.author(author)
//                            .enableSwagger() // 开启 swagger 模式
                            .outputDir(outputDir);
                })
                .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                    int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                    if (typeCode == Types.SMALLINT) {
                        // 自定义类型转换
                        return DbColumnType.INTEGER;
                    }
                    if (typeCode == Types.BIGINT) {
                        return DbColumnType.STRING;
                    }
                    if (typeCode == Types.TINYINT) {
                        return DbColumnType.INTEGER;
                    }
                    return typeRegistry.getColumnType(metaInfo);
                }))

                .packageConfig(builder -> {
                    builder.entity(entityPackageName)
                            .controller(controllerPackageName)
                            .mapper(mapperPackageName)
                            .service(servicePackageName)
                            .serviceImpl(serviceImplPackageName)
                            .parent(parent) // 设置父包名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, mapperXmlPath)); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {

                    builder.controllerBuilder()
                            .enableFileOverride()
                            .enableRestStyle();

                    builder.serviceBuilder()
                            .enableFileOverride()
                            .superServiceClass(superServiceName)
                            .superServiceImplClass(superServiceImplName)
                            .build();

                    builder.mapperBuilder()
                            .enableBaseColumnList()
                            .enableBaseResultMap()
                            .enableFileOverride();
                    builder.entityBuilder()
                            .enableColumnConstant()
                            .addTableFills(fillColumns)
                            .enableFileOverride()
                            .enableLombok()
                            .idType(IdType.ASSIGN_ID) // 主键类型，生成策略
                            .enableTableFieldAnnotation()
                            .naming(NamingStrategy.underline_to_camel)
                            .disableSerialVersionUID()
                            .enableActiveRecord() // 开启 ActiveRecord 模式
                            .enableChainModel(); // 开启链式模型
                    builder
                            .addInclude(generatorTables)
                            .addTablePrefix(tablePrefix)// 设置过滤表前缀
                            .addFieldPrefix(fieldPrefix);
                })
                .execute();
    }

    static class ModuleTableGenerator {
        public static Map<String, String[]> moduleTablesMap = new HashMap<>();

        private static void getFileTableNames() throws ClassNotFoundException {
            String moduleName = "system";
            String path = "C:\\Users\\Administrator\\IdeaProjects\\cmttg\\cmttg-common\\src\\main\\java\\com\\xwtec\\cmttg\\common\\pojo\\" + moduleName;

            String packageName = "com.xwtec.cmttg.common.pojo." + moduleName;
            File file = new File(path);
            for (File listFile : file.listFiles()) {
                String className = packageName + "." + listFile.getName().replace(".java", "");
                Class<?> aClass = ClassUtils.getClass(className);
                TableName annotation = aClass.getAnnotation(TableName.class);
                System.err.print(",\"" + annotation.value() + "\"");
            }
        }
    }
}
